<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发票管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            display: flex;
            min-height: 100vh;
        }

        /* 左侧导航栏 */
        .side-menu-container {
            width: 200px;
            background-color: #f0f0f0;
            height: 100vh;
        }

        .side-menu {
            list-style: none;
            padding: 20px 0;
        }

        .side-menu li {
            padding: 15px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .side-menu li:hover {
            background-color: #e0e0e0;
        }

        .side-menu li.active {
            background-color: #0277bd;
            color: white;
        }

        /* 右侧内容区 */
        .content-container {
            flex: 1;
            padding: 20px;
            background-color: #f8f9fa;
        }

        .content {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .header {
            background-color: #0277bd;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .btn {
            padding: 10px 15px;
            background-color: #0277bd;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn:hover {
            background-color: #01579b;
        }

        .table-container {
            overflow-x: auto;
            margin-top: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f5f5f5;
            font-weight: bold;
        }

        .pagination {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
        }

        .pagination-controls button {
            padding: 5px 10px;
            margin-right: 5px;
        }

        /* 图片预览 */
        .image-preview {
            width: 200px;
            height: 200px;
            border: 1px solid #ddd;
            margin: 15px 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* 图片预览样式 */
        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            border: 1px solid #ddd;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <!-- 左侧导航栏 -->
    <div class="side-menu-container">
        <ul class="side-menu" id="side-menu">
            <li class="active" data-page="personal-info">个人信息</li>
            <li data-page="invoice-upload">发票上传</li>
            <li data-page="invoice-query">发票查询</li>
            <li data-page="invoice-stats">发票统计</li>
        </ul>
    </div>

    <!-- 右侧内容区 -->
    <div class="content-container">
        <div class="header">
            <h1 id="page-title">发票管理系统</h1>
            <div id="user-info">当前用户: test_user</div>
        </div>

        <div class="content" id="content">
            <!-- 个人信息页面 -->
            <div id="personal-info-page" class="page">
                <h2>个人信息</h2>
                <div class="form-group">
                    <label>单位全称：</label>
                    <span id="company-name"></span>
                </div>
                <div class="form-group">
                    <label>统一社会信用代码：</label>
                    <span id="credit-code"></span>
                </div>
                <div class="form-group">
                    <label>邮箱：</label>
                    <span id="email"></span>
                </div>
                <div class="form-group">
                    <label>联系电话：</label>
                    <span id="phone"></span>
                </div>
                <div class="form-group">
                    <label>地址：</label>
                    <span id="address"></span>
                </div>
                <div class="form-group">
                    <label>开户银行：</label>
                    <span id="bank"></span>
                </div>
                <div class="form-group">
                    <label>银行卡号：</label>
                    <span id="bank-account"></span>
                </div>
            </div>

            <!-- 发票上传页面 -->
            <div id="invoice-upload-page" class="page" style="display: none;">
                <h2>发票上传</h2>
                <div id="progress-container" style="margin: 15px 0; display: none;">
                    <div id="progress-bar" style="width: 0%; height: 20px; background: #0277bd; transition: width 0.3s;"></div>
                    <div id="progress-text" style="text-align: center; margin-top: 5px;">0%</div>
                </div>

                <div class="form-group">
                    <label>选择发票图片：</label>
                    <input type="file" id="invoice-file" accept="image/*">
                </div>
                <div class="image-preview" id="image-preview">
                    <span>预览图片</span>
                </div>
                <button class="btn" id="upload-invoice">上传</button>
            </div>

            <!-- 发票查询页面 -->
            <div id="invoice-query-page" class="page" style="display: none;">
                <h2>发票查询</h2>
                <div class="form-group">
                    <label>发票编号：</label>
                    <input type="text" id="invoice-id" placeholder="请输入发票编号">
                </div>
                <div class="form-group">
                    <label>开票单位：</label>
                    <input type="text" id="selling-company" placeholder="请输入开票单位">
                </div>
                <div class="form-group">
                    <label>开始日期：</label>
                    <input type="date" id="start-date">
                </div>
                <div class="form-group">
                    <label>结束日期：</label>
                    <input type="date" id="end-date">
                </div>
                <div class="form-group" style="display: flex; gap: 10px;">
                    <button class="btn" id="query-invoices">查询</button>
                    <button class="btn" style="background-color: #f44336;" id="reset-query">重置</button>
                </div>
                <div class="table-container">
                    <table id="invoices-table">
                        <thead>
                            <tr>
                                <th>发票编号</th>
                                <th>开票单位</th>
                                <th>开票日期</th>
                                <th>金额</th>
                                <th>发票类型</th>
                                <th>查看发票图片</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 表格数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
                <div class="pagination">
                    <div class="pagination-info">共 <span id="total-records">0</span> 条记录 第 <span id="current-page">1</span> / <span id="total-pages">1</span> 页</div>
                    <div class="pagination-controls">
                        <button id="first-page">第一页</button>
                        <button id="prev-page">上一页</button>
                        <button id="next-page">下一页</button>
                        <select id="page-size">
                            <option value="10">10条/页</option>
                            <option value="20">20条/页</option>
                            <option value="50">50条/页</option>
                        </select>
                        <span>跳至</span>
                        <input type="number" id="goto-page" min="1" style="width: 50px;">
                        <span>页</span>
                    </div>
                </div>
            </div>

            <!-- 发票统计页面 -->
            <div id="invoice-stats-page" class="page" style="display: none;">
                <h2>发票统计</h2>
                <div class="form-group">
                    <label>开票单位：</label>
                    <input type="text" id="stats-selling-company" placeholder="请输入开票单位">
                </div>
                <div class="form-group">
                    <label>开始日期：</label>
                    <input type="date" id="stats-start-date">
                </div>
                <div class="form-group">
                    <label>结束日期：</label>
                    <input type="date" id="stats-end-date">
                </div>
                <button class="btn" id="stats-invoices">统计</button>
                <div class="table-container">
                    <table id="stats-table">
                        <thead>
                            <tr>
                                <th>统计项目</th>
                                <th>数值</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>总发票数量</td>
                                <td id="total-count"></td>
                            </tr>
                            <tr>
                                <td>总金额</td>
                                <td id="total-amount"></td>
                            </tr>
                        </tbody>
                    </table>
                    <br>
                    <table id="details-table">
                        <thead>
                            <tr>
                                <th>发票编号</th>
                                <th>开票单位</th>
                                <th>开票日期</th>
                                <th>金额</th>
                                <th>发票类型</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 表格数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 页面切换逻辑
        document.addEventListener('DOMContentLoaded', function() {
            const sideMenuItems = document.querySelectorAll('#side-menu li');
            const pages = document.querySelectorAll('.page');

            sideMenuItems.forEach(item => {
                item.addEventListener('click', function() {
                    // 移除所有菜单项的active类
                    sideMenuItems.forEach(li => li.classList.remove('active'));
                    // 为当前点击的菜单项添加active类
                    this.classList.add('active');

                    // 隐藏所有页面
                    pages.forEach(page => page.style.display = 'none');

                    // 显示对应页面
                    const pageId = this.getAttribute('data-page') + '-page';
                    document.getElementById(pageId).style.display = 'block';

                    // 更新页面标题
                    document.getElementById('page-title').textContent = this.textContent;
                });
            });

            // 获取个人信息
            fetch('/api/profile')
              .then(response => response.json())
              .then(data => {
                    if (data.success) {
                        const user = data.user;
                        document.getElementById('company-name').textContent = user.company_name;
                        document.getElementById('credit-code').textContent = user.username;
                        document.getElementById('email').textContent = user.email;
                        document.getElementById('phone').textContent = user.phone;
                        document.getElementById('address').textContent = user.address;
                        document.getElementById('bank').textContent = user.bank_name;
                        const bankAccount = user.bank_account;
                        const maskedAccount = bankAccount.slice(0, 2) + '*'.repeat(bankAccount.length - 2);
                        document.getElementById('bank-account').textContent = maskedAccount;
                    } else {
                        alert('获取个人信息失败: ' + data.message);
                    }
                })
              .catch(error => {
                    console.error('Error:', error);
                    alert('获取个人信息过程中发生错误');
                });

            // 发票上传功能
            const invoiceFileInput = document.getElementById('invoice-file');
            const imagePreview = document.getElementById('image-preview');
            const uploadInvoiceBtn = document.getElementById('upload-invoice');

            invoiceFileInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        imagePreview.innerHTML = `<img src="${event.target.result}" width="200" height="200">`;
                    };
                    reader.readAsDataURL(file);
                }
            });

            uploadInvoiceBtn.addEventListener('click', function() {
                const fileInput = document.getElementById('invoice-file');
                const file = fileInput.files[0];
                if (!file) {
                    alert('请选择发票图片');
                    return;
                }

                // 显示进度条
                const progressContainer = document.getElementById('progress-container');
                const progressBar = document.getElementById('progress-bar');
                const progressText = document.getElementById('progress-text');
                progressContainer.style.display = 'block';

                // 使用 XMLHttpRequest 实现进度监听
                const xhr = new XMLHttpRequest();
                const formData = new FormData();
                formData.append('file', file);

                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percent = (e.loaded / e.total * 100).toFixed(2);
                        progressBar.style.width = percent + '%';
                        progressText.textContent = percent + '%';
                    }
                });

                xhr.addEventListener('load', function() {
                    if (xhr.status === 200) {
                        const data = JSON.parse(xhr.responseText);
                        if (data.success) {
                            alert('发票上传成功！');
                            fileInput.value = '';
                            imagePreview.innerHTML = '<span>预览图片</span>';
                        } else {
                            alert('上传失败: ' + data.message);
                        }
                    } else {
                        alert('上传过程中发生错误');
                    }
                    progressContainer.style.display = 'none';
                });

                xhr.open('POST', '/api/upload');
                xhr.send(formData);
            });

            // 发票查询功能
            const queryInvoicesBtn = document.getElementById('query-invoices');
            const resetQueryBtn = document.getElementById('reset-query');
            const invoicesTable = document.getElementById('invoices-table').getElementsByTagName('tbody')[0];

            queryInvoicesBtn.addEventListener('click', function(e) {
    e.preventDefault(); // 阻止表单默认提交
    const invoiceId = document.getElementById('invoice-id').value.trim();
    const sellingCompany = document.getElementById('selling-company').value.trim();
    const startDate = document.getElementById('start-date').value;
    const endDate = document.getElementById('end-date').value;

    // 构建查询参数
    const params = new URLSearchParams();
    if (invoiceId) params.append('invoice_id', invoiceId);
    if (sellingCompany) params.append('selling_company', sellingCompany);
    if (startDate) params.append('start_date', startDate);
    if (endDate) params.append('end_date', endDate);

    // 打印请求参数
    console.log('查询参数:', params.toString());

    // 发送请求
    fetch(`/api/invoices?${params.toString()}`)
      .then(response => {
            console.log('服务器响应状态:', response.status);
            if (!response.ok) throw new Error('网络响应异常');
            return response.json();
        })
      .then(data => {
            console.log('服务器返回数据:', data);
            if (data.success) {
                // 清空表格
                invoicesTable.innerHTML = '';

                // 填充表格数据
                data.invoices.forEach(invoice => {
                    const row = invoicesTable.insertRow();
                    row.insertCell(0).textContent = invoice.invoice_id || '';
                    row.insertCell(1).textContent = invoice.selling_company || '';
                    row.insertCell(2).textContent = invoice.issue_date || '';
                    row.insertCell(3).textContent = invoice.amount || '';
                    row.insertCell(4).textContent = invoice.type || '';
                    const imageCell = row.insertCell(5);
                    if (invoice.filename) {
                        // 使用正确的图片文件名构造图片URL
                        const imageLink = document.createElement('a');
                        imageLink.href = `/uploads/${invoice.filename}`;
                        imageLink.target = '_blank';
                        imageLink.textContent = '查看图片';
                        imageCell.appendChild(imageLink);
                    } else {
                        imageCell.textContent = '无图片';
                    }
                });

                // 更新分页信息
                document.getElementById('total-records').textContent = data.total_records;
                document.getElementById('current-page').textContent = data.current_page;
                document.getElementById('total-pages').textContent = data.total_pages;
            } else {
                alert('查询失败: ' + data.message);
            }
        })
      .catch(error => {
            console.error('Error:', error);
            alert('查询过程中发生错误');
        });
});

            resetQueryBtn.addEventListener('click', function() {
                document.getElementById('invoice-id').value = '';
                document.getElementById('selling-company').value = '';
                document.getElementById('start-date').value = '';
                document.getElementById('end-date').value = '';
            });

            // 分页功能
            document.getElementById('first-page').addEventListener('click', function() {
                // 实现分页逻辑
            });

            document.getElementById('prev-page').addEventListener('click', function() {
                // 实现分页逻辑
            });

            document.getElementById('next-page').addEventListener('click', function() {
                // 实现分页逻辑
            });

            // 发票统计功能
            const statsInvoicesBtn = document.getElementById('stats-invoices');
            const totalCountElement = document.getElementById('total-count');
            const totalAmountElement = document.getElementById('total-amount');
            const detailsTable = document.getElementById('details-table').getElementsByTagName('tbody')[0];

            statsInvoicesBtn.addEventListener('click', function() {
                const sellingCompany = document.getElementById('stats-selling-company').value.trim();
                const startDate = document.getElementById('stats-start-date').value;
                const endDate = document.getElementById('stats-end-date').value;

                // 构建查询参数
                const params = new URLSearchParams();
                if (sellingCompany) params.append('selling_company', sellingCompany);
                if (startDate) params.append('start_date', startDate);
                if (endDate) params.append('end_date', endDate);

                // 发送请求
                fetch(`/api/invoice_stats?${params.toString()}`)
                  .then(response => {
                        if (!response.ok) throw new Error('网络响应异常');
                        return response.json();
                    })
                  .then(data => {
                        if (data.success) {
                            // 更新统计信息
                            totalCountElement.textContent = data.total_count;
                            totalAmountElement.textContent = data.total_amount;

                            // 清空明细表格
                            detailsTable.innerHTML = '';

                            // 填充明细表格数据
                            data.details.forEach(invoice => {
                                const row = detailsTable.insertRow();
                                row.insertCell(0).textContent = invoice.invoice_id || '';
                                row.insertCell(1).textContent = invoice.selling_company || '';
                                row.insertCell(2).textContent = invoice.issue_date || '';
                                row.insertCell(3).textContent = invoice.amount || '';
                                row.insertCell(4).textContent = invoice.type || '';
                            });
                        } else {
                            alert('统计失败: ' + data.message);
                        }
                    })
                  .catch(error => {
                        console.error('Error:', error);
                        alert('统计过程中发生错误');
                    });
            });
        });
    </script>
</body>
</html>